import React, { useState, useEffect } from 'react';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import ImageGrid from '../components/ImageGrid';
import API_CONFIG from '../utils/apiConfig';

const ITEMS_PER_PAGE = 8;

const ChannelPage = () => {
  const [channels, setChannels] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [currentPage, setCurrentPage] = useState(1);
  const [selectedChannel, setSelectedChannel] = useState(null); // 选中的通道
  const [showModal, setShowModal] = useState(false); // 是否显示模态窗口

  // 获取通道数据
  useEffect(() => {
    const  fetchChannels = async () => {
      try {
        setLoading(true);
        
        // 从后端API获取channel表中config_id为VITE_CONFIG_ID的所有channel信息
        const configId = import.meta.env.VITE_CONFIG_ID;
        if (!configId) {
          throw new Error('VITE_CONFIG_ID环境变量未设置');
        }
        
        const response = await fetch(`${API_CONFIG.baseURL}/channels?config_id=${configId}`);
        
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const channelData = await response.json();
        
        // 格式化通道数据以适配前端显示
        const formattedChannels = channelData.map(channel => ({
          id: `${channel.channel_id-1}`,
          title: `通道 ${channel.channel_id}`,
          thumbnail: API_CONFIG.getURL('images') + '/placeholder.jpg',
          views: 0,
          channel: `${channel.channel_id-1}`
        }));
        
        setChannels(formattedChannels);
        setError(null);
        console.log(`成功加载配置ID为${configId}的通道数据:`, formattedChannels);
      } catch (err) {
        setError('无法加载通道数据');
        console.error('Error fetching channels:', err);
        
        // 如果API调用失败，使用默认的占位数据作为fallback
        const channelData = [];
        for (let channel = 0; channel < 8; channel++) {
          channelData.push({
            id: channel,
            title: `通道 ${channel}`,
            thumbnail: API_CONFIG.getURL('images') + '/placeholder.jpg',
            views: 0,
            channel: channel
          });
        }
        setChannels(channelData);
      } finally {
        setLoading(false);
      }
    };

    fetchChannels();
  }, []);

  // 处理通道点击事件，显示模态窗口
  const handleChannelClick = (channel) => {
    setSelectedChannel(channel);
    setShowModal(true);
  };

  // 关闭模态窗口
  const handleCloseModal = () => {
    setShowModal(false);
    setSelectedChannel(null);
  };

  // 模态窗口组件
  const Modal = () => {
    const [videoError, setVideoError] = useState(false);
    const [isPlaying, setIsPlaying] = useState(false);
    const [streamUrl, setStreamUrl] = useState('');
    const videoRef = React.useRef(null);

    // 根据MediaMTX配置生成视频流URL
    const getStreamUrl = () => {
      const baseUrl = import.meta.env.VITE_MEDIAMTX_URL || 'http://172.25.6.39:8889';
      const streamName = `channel_${selectedChannel}`;
      const streamUrl = `${baseUrl}/${streamName}`;
      
      console.log('生成的视频流URL:', streamUrl);
      console.log('MediaMTX基础URL:', baseUrl);
      console.log('通道编号:', selectedChannel);
      
      return streamUrl;
    };

    useEffect(() => {
      if (!showModal) {
        // 关闭模态窗口时重置状态
        setIsPlaying(false);
        setVideoError(false);
        return;
      }
      
      // 立即设置WebRTC流URL，减少延迟
      const url = getStreamUrl();
      setStreamUrl(url);
      
      console.log('立即加载WebRTC流:', url);
      
      // 立即开始加载，不添加延迟
      setVideoError(false);
      setIsPlaying(true);
      
      // 强制iframe重新加载以确保最新流
      const timer = setTimeout(() => {
        const iframe = document.getElementById('webrtc-stream');
        if (iframe && iframe.src === url) {
          // 如果iframe已经加载了正确的URL，强制重新加载
          iframe.src = iframe.src;
        }
      }, 500);
      
      return () => clearTimeout(timer);
    }, [showModal, selectedChannel]);

    const handleVideoError = () => {
      console.error('视频流加载失败');
      setVideoError(true);
      setIsPlaying(false);
    };

    const handleVideoLoad = () => {
      console.log('视频流加载成功');
      setVideoError(false);
    };

    const handlePlayPause = () => {
      if (videoRef.current) {
        if (isPlaying) {
          videoRef.current.pause();
          setIsPlaying(false);
        } else {
          videoRef.current.play().then(() => {
            setIsPlaying(true);
          }).catch(err => {
            console.error('播放失败:', err);
            setVideoError(true);
          });
        }
      }
    };

    // 重新加载视频
    const reloadVideo = () => {
      setVideoError(false);
      setIsPlaying(false);
      if (videoRef.current) {
        videoRef.current.load();
      }
    };

    if (!showModal) return null;

    return (
      <div className="modal-overlay" onClick={handleCloseModal}>
        <div className="modal-content" onClick={(e) => e.stopPropagation()}>
          <button className="modal-close" onClick={handleCloseModal}>
            ×
          </button>
          <h3>通道 {selectedChannel} 实时画面</h3>
          
          {/* 流类型显示 */}          
          <div className="video-container">
            {videoError ? (
              <div className="video-error">
                <p>视频流加载失败</p>
                <p>请检查MediaMTX服务或流配置</p>
                <button onClick={() => {
                  setVideoError(false);
                  // 重新加载iframe
                  const iframe = document.getElementById('webrtc-stream');
                  if (iframe) {
                    iframe.src = iframe.src;
                  }
                }}>重试</button>
              </div>
            ) : (
              <>
                {streamUrl ? (
                  <iframe
                    id="webrtc-stream"
                    src={streamUrl}
                    style={{ 
                      width: '100%', 
                      height: '576px',
                      border: 'none',
                      borderRadius: '8px'
                    }}
                    allow="autoplay; fullscreen"
                    onLoad={handleVideoLoad}
                    onError={handleVideoError}
                    sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
                  />
                ) : (
                  <div className="video-loading">
                    <p>正在加载视频流...</p>
                  </div>
                )}
              </>
            )}
          </div>
        </div>
      </div>
    );
  };

  // 计算分页
  const totalPages = Math.ceil(channels.length / ITEMS_PER_PAGE);
  const startIndex = (currentPage - 1) * ITEMS_PER_PAGE;
  const endIndex = startIndex + ITEMS_PER_PAGE;
  const currentChannels = channels.slice(startIndex, endIndex);

  const handlePageChange = (page) => {
    setCurrentPage(page);
    window.scrollTo({ top: 0, behavior: 'smooth' });
  };

  const renderPagination = () => {
    if (totalPages <= 1) return null;

    const pages = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);

    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    // 上一页按钮
    pages.push(
      <button
        key="prev"
        onClick={() => handlePageChange(currentPage - 1)}
        disabled={currentPage === 1}
        className="pagination-btn"
      >
        <ChevronLeft size={16} />
      </button>
    );

    // 页码
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          onClick={() => handlePageChange(i)}
          className={`pagination-btn ${currentPage === i ? 'active' : ''}`}
        >
          {i}
        </button>
      );
    }

    // 下一页按钮
    pages.push(
      <button
        key="next"
        onClick={() => handlePageChange(currentPage + 1)}
        disabled={currentPage === totalPages}
        className="pagination-btn"
      >
        <ChevronRight size={16} />
      </button>
    );

    return (
      <div className="pagination">
        <span className="pagination-info">
          第 {currentPage} 页，共 {totalPages} 页 ({channels.length} 个通道)
        </span>
        <div className="pagination-controls">
          {pages}
        </div>
      </div>
    );
  };

  if (loading) {
    return (
      <div className="image-grid-page">
        <h2>实时画面</h2>
        <div className="loading">加载中...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="image-grid-page">
        <h2>实时画面</h2>
        <div className="error">
          <h3>{error}</h3>
          <p>请检查网络连接或稍后重试</p>
        </div>
      </div>
    );
  }

  return (
    <div className="image-grid-page">
      <h2>实时画面</h2>
      <ImageGrid images={currentChannels} onImageClick={handleChannelClick} />
      {renderPagination()}
      <Modal />
    </div>
  );
};

export default ChannelPage;
